package com.p2p.backend.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.p2p.backend.model.P2PRecharge;
import com.p2p.backend.model.P2PRecharge.Status;
import com.p2p.backend.service.ExportService;
import com.p2p.backend.service.OplogService;
import com.p2p.backend.service.P2PRechargeService;
import com.p2p.backend.util.PageUtils;
import com.p2p.base.annotation.PermissionNeed;
import com.p2p.base.model.Action;
import com.p2p.base.model.Module;
import com.p2p.base.model.Money;
import com.p2p.base.model.Oplog;
import com.p2p.base.page.PageVo;
import com.p2p.base.web.controller.BaseController;
import com.p2p.front.dal.model.User;
import com.p2p.front.service.UserService;

/**
 * @author leiwen@yiqihao.com
 *
 */
@Controller
@RequestMapping("/recharge")
public class RechargeController extends BaseController {

	@Resource
	private P2PRechargeService p2pRechargeService;
	
	@Resource
	private UserService userService;
	
	@Resource
	private ExportService exportService;

	@PermissionNeed("recharge_list")
	@RequestMapping("/list")
	public void list(PageVo form, Model model) {
		form.handleSearch();
		PageVo page = p2pRechargeService.listPage(form);
		
		model.addAttribute("res", 1);
		form.resetSearch();
		Map<String, Object> data = PageUtils.data(page);

		model.addAttribute("data", data);
		{
			List<Map<String, Object>> rows = (List<Map<String, Object>>) data
					.get("rows");
			List<String> uidList = new ArrayList<String>();
			for (Map<String, Object> oneRow : rows) {
				uidList.add(oneRow.get("uid").toString());
			}
			Map<String, User> userMap = userService.searchUserByIdList(uidList);
			for (Map<String, Object> oneRow : rows) {
				String uid = oneRow.get("uid").toString();
				User user = userMap.get(uid);
				if (user != null) {
					oneRow.put("umobile", user.getUmobile());
					oneRow.put("uname", user.getUname());
					oneRow.put("realname", user.getRealname());
				}

			}
		}
		List<Map<String, Object>> footer = new ArrayList<Map<String, Object>>();
		data.put("footer", footer);
		Map<String, Object> footerOne = new HashMap<String, Object>();
		// Map<String,Object> footerTwo =new HashMap<String,Object>();
		footer.add(footerOne);
		// footer.add(footerTwo);

		if (page.getTotalCount() > 0) {
			Map<String, Object> parames = new HashMap<String, Object>();
			parames.put("startData", form.getStartDate());
			parames.put("endData", form.getEndDate());
			Money amount = p2pRechargeService.sumForCondition(parames);
			footerOne.put("trade_account", "成功金额");
			footerOne.put("money", amount.getCent());

		} else {
			footerOne.put("trade_account", "成功金额");
			footerOne.put("money", 0);
		}

		footerOne.put("type", "总笔数");
		footerOne.put("trade_no", page.getTotalCount());

	}

	@PermissionNeed("recharge_dopayment")
	@RequestMapping("/doPayment")
	public void doPayment(@RequestParam Long id, HttpServletRequest request,
			Model model) {
		//重复支付检查,成功状态的，不允许再次支付
		int succeed=Status.SUCCESS.getStatus();
		P2PRecharge recharge=p2pRechargeService.findP2PRechargeById(id);
		Oplog oplog = super.oplog(request);
		oplog.setModule(Module.FUNDS_RECHARGE);
		oplog.setAction(Action.UPDATE);
		oplog.setParams("id="+id);
	
		if(recharge.getStatus()==succeed){
			model.addAttribute("res",0);
			oplog.setRemark("重复支付，failed");
		}else{
			p2pRechargeService.doPayment(id,getRemoteIp(request));
			model.addAttribute("res", 1);
			oplog.setRemark("支付成功");
		}
		OplogService.log(oplog);
	}
	
	
	@RequestMapping("/doExport")
	public void doExportSuccese(PageVo form,HttpServletResponse response){
		
		//JSONObject json = new JSONObject();
		if(StringUtils.isBlank(form.getStartDate())||StringUtils.isBlank(form.getEndDate())){
			this.returnMessage(response, "开始结束时间不能为空");
			return;
		}
		form.getParams().put("status", "21");
		
		 try {
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(("充值流水"+form.getStartDate()+"-"+form.getEndDate()).getBytes(), "ISO-8859-1"));
			//设定输出文件头
			   response.setContentType("application/vnd.ms-excel;charset=UTF-8");// 定义输出类型 
			   // 通过response的输出流把工作薄的流发送浏览器形成文件
			   OutputStream outStream = response.getOutputStream();
			   exportService.exportSucceseRecharge(outStream, form);
			   return;
		 } catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 //失败或者异常
		 JSONObject jsonObject = new JSONObject();
			jsonObject.put("res", -1);
		this.returnJsonObject(response, jsonObject);
		return;
	}
}
